/**
 * This file is released under the GNU General Public License.
 * Refer to the COPYING file distributed with this package.
 *
 * Copyright (c) 2008-2009 WURFL-Pro srl
 */
package net.sourceforge.wurfl.core.request;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import net.sourceforge.wurfl.core.request.normalizer.UserAgentNormalizer;

/**
 * Chain of {@link UserAgentNormalizer}s.
 * 
 * <p>
 * Apply the normalizers as filters, to the target user-agent. All the
 * normalizer are applied, it is not a chain of responsibility.
 * <p/>
 * 
 * @author WURFL-PRO SRL, Rome, Italy
 * @version $Id: UserAgentNormalizerChain.java 1045 2009-03-09 15:52:53Z filippo.deluca $
 */
public class UserAgentNormalizerChain implements UserAgentNormalizer {

	/** List of UserAgentNormalizer */
	private final List/* UserAgentNormalizer */chain = new ArrayList();

	/**
	 * Default constructor.
	 */
	public UserAgentNormalizerChain() {
		// Empty
	}

	/**
	 * Constructor by list of UserAgentNormalizer.
	 * 
	 * @param normalizers
	 *            The List<UserAgentNormalizer> used to implement the chain.
	 */
	public UserAgentNormalizerChain(List/* UserAgentNormalizer */normalizers) {
		chain.addAll(normalizers);
	}

	/**
	 * Constructor by UserAgentNormalizer array.
	 * 
	 * @param normalizers
	 *            The UserAgentNormalizer array used to implement the chain.
	 */
	public UserAgentNormalizerChain(UserAgentNormalizer[] normalizers) {
		this(Arrays.asList(normalizers));
	}

	/**
	 * Add a UserAgentNormalizer to the chain.
	 * 
	 * @param userAgentNormalizer
	 *            The UserAgentNormalizer to add.
	 */
	public void add(UserAgentNormalizer userAgentNormalizer) {
		chain.add(userAgentNormalizer);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * Applies all UserAgentNormalizer to the target user-agent.
	 */
	public String normalize(String userAgent) {
		String normalized = userAgent;
		for (Iterator iterator = chain.iterator(); iterator.hasNext();) {
			UserAgentNormalizer userAgentNormalizer = (UserAgentNormalizer) iterator
					.next();
			normalized = userAgentNormalizer.normalize(normalized);
		}

		return normalized;
	}

	/**
	 * Return all UserAgentNormalizers managed by this chain.
	 * 
	 * @return List<UserAgentNormalizer> contains all UserAgentNormalizer used
	 *         by this chain.
	 */
	public List getAllNormalizers() {
		return Collections.unmodifiableList(chain);
	}
}
